//
//  ZPickerView.m
//  ArkHealth
//
//  Created by 章翔 on 16/9/13.
//  Copyright © 2016年 xjx. All rights reserved.
//

#import "ZPickerView.h"
#import "ZActionSheet.h"



@implementation AreaData

@end

@implementation PickerModel

@end


@interface ZPickerView()<UIPickerViewDelegate,UIPickerViewDataSource>
@property(nonatomic, assign)EPickerMode pickMode;//<

@property(nonatomic, strong)NSMutableArray *mArrDatas;//<

@property(nonatomic, strong)NSString *strChoose;//<

@property(nonatomic, strong)AreaData *city;//<
@property(nonatomic, strong)AreaData *provice;//<


@property(nonatomic, strong)NSString *dateStr;//< 日期
@property(nonatomic, strong)NSString *timeStr;//< 时间

@property(nonatomic, assign)int selectIndex;//< 一行选中的index

@property(nonatomic, strong)PickerModel *selectModel;

@property(nonatomic, strong)NSMutableArray *mArrCarNum;
@property(nonatomic, strong)NSMutableArray *mArrChar;
@property(nonatomic, strong)NSString *carProvice;
@property(nonatomic, strong)NSString *charCapital;

@property(nonatomic,strong)NSMutableArray *mArrBeginDate;
@property(nonatomic,strong)NSMutableArray *mArrEndDate;
@property(nonatomic,strong)NSDate *dateBegin;
@property(nonatomic,strong)NSDate *dateEnd;

@property(nonatomic,strong)UIPickerView *pickView;
@end

@implementation ZPickerView{
    void (^_block)(NSObject *obj);
    void (^_block1)(PickerModel *model);
    void (^_block2)(NSDate *dateBegin,NSDate *dateEnd);
}

+ (ZPickerView *)pickerView {
    static ZPickerView *pickerView;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        pickerView = [[self alloc] init];
        //        sharedView.autoCorner = YES;
    });
    
    return pickerView;
}

+ (void )pickviewWithMode:(EPickerMode)mode dataSource:(NSMutableArray *)dataSource block:(void (^)(NSObject *obj))block{
     [[ZPickerView pickerView] pickviewWithMode:mode dataSource:dataSource block:block];
}

+ (void)pickviewWithSingerDataSouce:(NSMutableArray<PickerModel *> *)mArrDatas block:(void (^)(PickerModel *))block{
    [[ZPickerView pickerView] pickviewWithSingerDataSouce:mArrDatas block:block];
}

+ (void)pickviewWithHotelTimeBlock:(void(^)(NSDate *startDate,NSDate *endDate))block{
    [[ZPickerView pickerView]pickviewWithHotelTimeBlock:block];
}

- (void)pickviewWithSingerDataSouce:(NSMutableArray<PickerModel *> *)mArrDatas block:(void (^)(PickerModel *))block{
    _block1= block;
    CGFloat Wbtn = 60;
    CGFloat hbtn = 40;
    self.mArrDatas =  mArrDatas;
    if (mArrDatas.count>0) {
        _selectModel = mArrDatas.firstObject;
    }
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth - Wbtn, 0, Wbtn, hbtn)];
    [btn setTitle:@"确定" forState:UIControlStateNormal];
    [btn setTitleColor:UIColorFromRGB(0x4864f3) forState:UIControlStateNormal];
    btn.titleLabel.font = FontRegular(15);
    [self addSubview:btn];
    [btn addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
    self.pickMode = EPickerModeSinger1;
    self.backgroundColor = [UIColor whiteColor];
    
    UIButton *btnCancel = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, Wbtn, hbtn)];
    [btnCancel setTitle:@"取消" forState:UIControlStateNormal];
    [btnCancel setTitleColor:UIColorFromRGB(0x666666) forState:UIControlStateNormal];
    [self addSubview:btnCancel];
    btnCancel.titleLabel.font = FontRegular(15);
    [btnCancel addTarget:self action:@selector(onClickCancle:) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(14, 40, ScreenWidth - 14 * 2, 0.5)];
    line.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self addSubview:line];
    
    CGFloat HView = 200;
    self.frame = CGRectMake(0, 0, ScreenWidth, HView);
    
    UIPickerView *pickView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, hbtn, ScreenWidth, HView - hbtn)];
    pickView.delegate = self;
    pickView.dataSource = self;
    [self addSubview:pickView];
}

- (void)pickviewWithHotelTimeBlock:(void(^)(NSDate *startDate,NSDate *endDate))block{
    CGFloat Wbtn = 60;
    CGFloat hbtn = 40;
    _block2 = block;
    _mArrBeginDate = [NSMutableArray array];
    _mArrEndDate = [NSMutableArray array];
    self.pickMode = EPickerModeHotel;
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth - Wbtn, 0, Wbtn, hbtn)];
    [btn setTitle:@"确定" forState:UIControlStateNormal];
    [btn setTitleColor:UIColorFromRGB(0x4864f3) forState:UIControlStateNormal];
    btn.titleLabel.font = FontRegular(15);
    [self addSubview:btn];
    [btn addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
    self.backgroundColor = [UIColor whiteColor];
    
    UIButton *btnCancel = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, Wbtn, hbtn)];
    [btnCancel setTitle:@"取消" forState:UIControlStateNormal];
    [btnCancel setTitleColor:UIColorFromRGB(0x666666) forState:UIControlStateNormal];
    [self addSubview:btnCancel];
    btnCancel.titleLabel.font = FontRegular(15);
    [btnCancel addTarget:self action:@selector(onClickCancle:) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(14, 40, ScreenWidth - 14 * 2, 0.5)];
    line.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self addSubview:line];
    
    CGFloat HView = 250;
    self.frame = CGRectMake(0, 0, ScreenWidth, HView);
    
    for (int i = 0; i < 2; i ++) {
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(14 + ((ScreenWidth - 14 * 2)/2) * i, 40, ScreenWidth/2 - 7, 50)];
        lab.textColor = UIColorFromRGB(0x333333);
        lab.font = FontRegular(13);
        lab.textAlignment = NSTextAlignmentCenter;
        lab.text = i == 0 ? @"入店时间":@"离店时间";
        [self addSubview:lab];
    }
    
    UIPickerView *pickView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, hbtn + 50, ScreenWidth, HView - hbtn - 50)];
    pickView.delegate = self;
    pickView.dataSource = self;
    [self addSubview:pickView];
    
    for (int i = 0; i < 30; i ++) {
        NSDate *date = [NSDate date];
        NSDate *newDate = [date dateByAddingTimeInterval:60 * 60 * 24 * i];
        [_mArrBeginDate addObject:newDate];
        if (i == 0) {
            self.dateBegin = newDate;
        }
    }
    
    for (int i = 0; i < 30; i ++) {
        NSDate *date = [NSDate date];
        NSDate *newDate = [date dateByAddingTimeInterval:60 * 60 * 24 * (i + 1)];
        [_mArrEndDate addObject:newDate];
        if (i == 0) {
            self.dateEnd = newDate;
        }
    }
}

- (void)pickviewWithMode:(EPickerMode)mode dataSource:(NSMutableArray *)dataSource block:(void (^)(NSObject *obj))block{
    _block= block;
    CGFloat Wbtn = 60;
    CGFloat hbtn = 40;
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth - Wbtn, 0, Wbtn, hbtn)];
    [btn setTitle:@"确定" forState:UIControlStateNormal];
    [btn setTitleColor:UIColorFromRGB(0x4864f3) forState:UIControlStateNormal];
    btn.titleLabel.font = FontRegular(15);
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self addSubview:btn];
    [btn addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
    self.pickMode = mode;
    self.backgroundColor = [UIColor whiteColor];

    UIButton *btnCancel = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, Wbtn, hbtn)];
    [btnCancel setTitle:@"取消" forState:UIControlStateNormal];
    [btnCancel setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self addSubview:btnCancel];
    [btnCancel addTarget:self action:@selector(onClickCancle:) forControlEvents:UIControlEventTouchUpInside];
    [btnCancel setTitleColor:UIColorFromRGB(0x666666) forState:UIControlStateNormal];
    btnCancel.titleLabel.font = FontRegular(15);

    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(14, 40, ScreenWidth - 14 * 2, 0.5)];
    line.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self addSubview:line];

    
    if (mode == EPickerModeErea) {
    
        
        self.mArrDatas = [NSMutableArray array];
        for (NSDictionary *provinceDic in dataSource) {
            AreaData *data = [[AreaData alloc]init];
            
            NSArray *citys = provinceDic[@"citys"];
            
            data.areaName =provinceDic[@"province"][@"name"];
            data.areaId = provinceDic[@"province"][@"code"];
            
            NSMutableArray *mArrCitys = [NSMutableArray array];
            for (NSDictionary *cityDic in citys) {
                AreaData *data = [[AreaData alloc]init];
                data.areaName =cityDic[@"name"];
                data.areaId = cityDic[@"code"];
                [mArrCitys addObject:data];
            }
            data.mArrCitys = mArrCitys;
            [self.mArrDatas addObject:data];
        }
        
        self.provice = self.mArrDatas.firstObject;
        
        self.city = self.provice.mArrCitys.firstObject;
  
    }
    else if (mode == EPickerModeSinger){
        self.mArrDatas = [NSMutableArray array];
        self.mArrDatas = dataSource;
        self.strChoose = dataSource.firstObject;
    }else if (mode == EPickerModeDate){
        self.mArrDatas = [NSMutableArray array];
        self.mArrDatas = dataSource;
        
        self.dateStr = [self.mArrDatas objectAtIndex:0][@"date"];
        NSDictionary *dict = [[self.mArrDatas objectAtIndex:0][@"times"] objectAtIndex:0];
        self.timeStr = dict[@"starttime"];

    }else if (mode == EPickerModeSinger1){
        self.mArrDatas = [NSMutableArray array];
        self.mArrDatas = dataSource;
        self.selectModel = [self.mArrDatas objectAtIndex:0];
    }else if (mode == EPickerModeCarDress){
        NSString *carNum = @"京津黑吉辽冀豫鲁晋陕蒙宁甘新青藏鄂皖苏沪浙闽湘赣川渝贵云粤桂琼";
        NSString *Char = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        
        self.mArrCarNum = [NSMutableArray array];
        self.mArrChar = [NSMutableArray array];
        for (int i = 0; i < carNum.length; i ++) {
            NSString *carStr = [carNum substringWithRange:NSMakeRange(i, 1)];
            [self.mArrCarNum addObject:carStr];
        }
        
        for (int i = 0; i < Char.length; i ++) {
            NSString *charStr = [Char substringWithRange:NSMakeRange(i, 1)];
            [self.mArrChar addObject:charStr];
        }
        self.charCapital = [self.mArrChar objectAtIndex:0];
        self.carProvice = [self.mArrCarNum objectAtIndex:0];
    }
    
    
    CGFloat HView = 200;
    self.frame = CGRectMake(0, 0, ScreenWidth, HView);
    
    UIPickerView *pickView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, hbtn, ScreenWidth, HView - hbtn)];
    pickView.delegate = self;
    pickView.dataSource = self;
    [self addSubview:pickView];
    self.pickView = pickView;
    
}

#pragma mark - PickerView lifecycle

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    if (self.pickMode == EPickerModeErea) {
        return 2;
    }else if(self.pickMode == EPickerModeSinger){
        return 1;
    }else if (self.pickMode == EPickerModeDate){
        return 2;
    }else if (self.pickMode == EPickerModeCarDress){
        return 2;
    }else if (self.pickMode == EPickerModeHotel){
        return 2;
    }
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (self.pickMode == EPickerModeSinger) {
        return self.mArrDatas.count;
    }
    else if (self.pickMode == EPickerModeErea){
        
        if (component == 0) {
            return self.mArrDatas.count;
        }else if(component == 1){
            
            AreaData *data = [self.mArrDatas objectAtIndex:self.selectIndex];
            return data.mArrCitys.count;

        }
    }else if (self.pickMode == EPickerModeDate){
        if (component == 0) {
            return self.mArrDatas.count;
        }else if (component == 1){
            NSDictionary *dict = [self.mArrDatas objectAtIndex:self.selectIndex];
            return [dict[@"times"] count];
        }
    }else if (self.pickMode == EPickerModeSinger1){
        return self.mArrDatas.count;
    }
    else if (self.pickMode == EPickerModeCarDress){
        if (component == 0) {
            return self.mArrCarNum.count;
        }else if (component == 1){
            return self.mArrChar.count;
        }
    }else if (self.pickMode == EPickerModeHotel){
        if (component == 0) {
            return self.mArrBeginDate.count;
        }else if (component == 1){
            return self.mArrEndDate.count;
        }
    }
    
    return 1;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel *lab = (UILabel *)view;
    if (view == nil) {
        lab = [[UILabel alloc]
               initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
        lab.textAlignment = NSTextAlignmentCenter;
        lab.textColor = [UIColor blackColor];
        lab.font = [UIFont systemFontOfSize:14];
    }
    
    NSString *title = nil;
    if (self.pickMode == EPickerModeSinger) {
        
        title = [self.mArrDatas objectAtIndex:row];
    }
    else if (self.pickMode == EPickerModeErea){
        
        if (component == 0) {
            AreaData *data = [self.mArrDatas objectAtIndex:row];
            title = data.areaName;

        }else if (component == 1){
            AreaData *data = [self.mArrDatas objectAtIndex:self.selectIndex];
            AreaData *dataCity = [data.mArrCitys objectAtIndex:row];
            title = dataCity.areaName;
        }
        
    }else if (self.pickMode == EPickerModeDate){
        if (component == 0) {
            NSDictionary *dict = [self.mArrDatas objectAtIndex:row];
            title = dict[@"date"];
            
        }else if (component == 1){
            NSDictionary *dict = [self.mArrDatas objectAtIndex:self.selectIndex];
            NSDictionary *timeDict = [dict[@"times"] objectAtIndex:row];
            title = timeDict[@"starttime"];
        }
    }else if (self.pickMode == EPickerModeSinger1){
        PickerModel *model = [self.mArrDatas objectAtIndex:row];
        title = model.name;
    }else if (self.pickMode == EPickerModeCarDress){
        
        if (component == 0) {
            title = [self.mArrCarNum objectAtIndex:row];
        }else if (component == 1){
            title = [self.mArrChar objectAtIndex:row];
            
        }
    }else if (self.pickMode == EPickerModeHotel){
        if (component == 0) {
            NSDate *date = [_mArrBeginDate objectAtIndex:row];
//            title = [ValidateHelper timeWithTimeIntervalDate:date andType:3];

            
            
        }else if (component == 1){
            NSDate *date = [_mArrEndDate objectAtIndex:row];
//            title = [ValidateHelper timeWithTimeIntervalDate:date andType:3];
        }
    }
    lab.text = title;
    return lab;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return 50;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    if (self.pickMode == EPickerModeErea) {
        
        if (component == 0) {
            self.selectIndex = row;
            [pickerView reloadComponent:1];
            [pickerView selectRow:0 inComponent:1 animated:YES];
            
            self.provice = [self.mArrDatas objectAtIndex:row];
            AreaData *data = [self.mArrDatas objectAtIndex:self.selectIndex];
            self.city = [data.mArrCitys objectAtIndex:0];
            
        }else if(component == 1){
            
            AreaData *data = [self.mArrDatas objectAtIndex:self.selectIndex];
            
            self.city = [data.mArrCitys objectAtIndex:row];
        }
        
    }
    else if (self.pickMode == EPickerModeSinger){
        self.strChoose = [self.mArrDatas objectAtIndex:row];
    }
    else if (self.pickMode == EPickerModeDate){
        if (component == 0) {
            self.selectIndex = row;
            [pickerView reloadComponent:1];
            [pickerView selectRow:0 inComponent:1 animated:YES];
            
            self.dateStr = [self.mArrDatas objectAtIndex:row][@"date"];
            
        }else if(component == 1){
            
            NSDictionary *dict = [self.mArrDatas objectAtIndex:self.selectIndex];
            
            self.timeStr = [dict[@"times"] objectAtIndex:row][@"starttime"];
        }

    
    }else if (self.pickMode == EPickerModeSinger1){
        self.selectModel = [self.mArrDatas objectAtIndex:row];
    }else if (self.pickMode == EPickerModeCarDress){
        if (component == 0) {
            self.selectIndex = row;
            [pickerView reloadComponent:1];
            [pickerView selectRow:0 inComponent:1 animated:YES];
            self.charCapital = self.mArrChar.firstObject;
            self.carProvice = self.mArrCarNum[row];
        }else if (component == 1){
            self.charCapital = self.mArrChar[row];
        }
    }else if (self.pickMode == EPickerModeHotel){
        if (component == 0) {
            _dateBegin = [_mArrBeginDate objectAtIndex:row];
            
            [_mArrEndDate removeAllObjects];
            for (int i = 0; i < 30; i ++) {
                NSDate *newDate = [_dateBegin dateByAddingTimeInterval:60 * 60 * 24 * (i + 1)];
                [_mArrEndDate addObject:newDate];
                if (i == 0) {
                    self.dateEnd = newDate;
                }
            }
            [pickerView reloadComponent:1];
            [pickerView selectRow:0 inComponent:1 animated:YES];
            
        }else if (component == 1){
            _dateEnd = [_mArrEndDate objectAtIndex:row];
        }
    }
    
    
}


- (void)onClick:(UIButton *)btn{
    
    
//    _block ()
    
    if (_block) {
        if (self.pickMode == EPickerModeErea) {
            
            
            _block(@[self.provice,self.city]);

        }
        else if (self.pickMode == EPickerModeSinger){
            _block(self.strChoose);
        }
        else if (self.pickMode == EPickerModeDate){
            NSString *string = [NSString stringWithFormat:@"%@ %@",self.dateStr,self.timeStr];
            _block(string);
        }else if (self.pickMode == EPickerModeCarDress){
            NSString *string = [NSString stringWithFormat:@"%@%@",self.carProvice,self.charCapital];
            _block(string);
        }
    }
    if (_block1) {
        _block1(_selectModel);
    }
    if (_block2) {
        
//        NSString *dateBeginString = [ValidateHelper timeWithTimeIntervalDate:self.dateBegin andType:3];
//        NSString *dateEndString = [ValidateHelper timeWithTimeIntervalDate:self.dateEnd andType:3];
//
//        NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
//        formatter.timeZone = [NSTimeZone timeZoneWithName:@"beijing"];
//        [formatter setDateStyle:NSDateFormatterMediumStyle];
//        [formatter setTimeStyle:NSDateFormatterShortStyle];
//        [formatter setDateFormat:@"yyyy-MM-dd"];
//        
//        NSDate *dateBeign1 = [formatter dateFromString:dateBeginString];
//        NSDate *dateEnd1 = [formatter dateFromString:dateEndString];
//        if (dateEnd1.timeIntervalSince1970 > dateBeign1.timeIntervalSince1970) {
//            _block2(dateBeign1,dateEnd1);
//        }else{
//            [ZXProgressHUD showErrorWithStatus:@"选择正确的时间"];
//        }
        
    }
    
    for (UIView *view in self.subviews) {
        [view removeFromSuperview];
    }
    [self removeFromSuperview];
    self.selectIndex = 0;
    [ZActionSheet dismiss];
}

- (void)onClickCancle:(UIButton*)btn{
    for (UIView *view in self.subviews) {
        [view removeFromSuperview];
    }
    self.selectIndex = 0;
    [self removeFromSuperview];
    
    [ZActionSheet dismiss];
}

+ (void)show{
    [ZActionSheet anctionSheetWithView:[ZPickerView pickerView]];
}

+ (void)dissmiss{
    [ZActionSheet dismiss];
}


+ (void)pickviewWithProvince:(NSString *)province city:(NSString *)city{
    [[ZPickerView pickerView]pickviewWithProvince:province city:city];
}

- (void)pickviewWithProvince:(NSString *)province city:(NSString *)city{
    int setion  = 0;
    int row = 0;
    
        for (int i = 0;i < self.mArrDatas.count ; i ++) {
            AreaData *data = [self.mArrDatas objectAtIndex:i];
            if ([data.areaName isEqualToString:province]) {
                setion = i;
                self.provice = data;
            }
            for (int j = 0 ; j < data.mArrCitys.count; j ++) {
                AreaData *dataCity = [data.mArrCitys objectAtIndex:j];
                    if ([dataCity.areaName isEqualToString:city]) {
                        row = j;
                        self.city = dataCity;
                    }
            }
        }
    [self.pickView selectRow:setion inComponent:0 animated:YES];
    [self.pickView selectRow:row inComponent:1 animated:YES];
    
}
@end
